﻿using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using Microsoft.WindowsLive.PublishPlugins;
using Tumblr.API;
using Tumblr.API.PostType;
using TumblrPlugin.Session;
using TumblrPlugin.Settings;

namespace TumblrPlugin
{
    public class TumblrPlugin: IPublishPlugin
    {
        private static TumblrApi _tumblrApi;

        public bool ShowConfigurationSettings(IWin32Window parentWindow, XmlDocument sessionXml, XmlDocument persistXml,
            IPublishProperties publishProperties)
        {
            var settingsForm = new SettingsForm(persistXml);
            var resultDialog = settingsForm.ShowDialog(parentWindow);

            if (resultDialog == DialogResult.OK)
            {
                var accountSettings = AccountSettings.Deserialize(persistXml);
                
                _tumblrApi = new TumblrApi(new Account(accountSettings.Email, accountSettings.Password));
                return true;
            }

            return false;
        }

        public bool PublishItem(IWin32Window parentWindow, string mediaObjectId, 
            Stream stream, XmlDocument sessionXml, IPublishProperties publishProperties, 
            IPublishProgressCallback callback, EventWaitHandle cancelEvent)
        {
            var photoGalleryPublishSession = PhotoGalleryPublishSession.Deserialize(sessionXml);
            foreach (var photoGalleryPublishItem in photoGalleryPublishSession.ItemSet)
            {
                var photo = new Photo
                                {
                                    Caption = String.IsNullOrEmpty(photoGalleryPublishItem.Title)
                                                  ? photoGalleryPublishItem.OriginalFileName
                                                  : photoGalleryPublishItem.Title,
                                    Data = photoGalleryPublishItem.FullFilePath
                                        
                                };

                foreach (var keyword in photoGalleryPublishItem.KeywordSet)
                {
                    photo.Tags += keyword + ",";
                }

                var status = _tumblrApi.PostPhoto(photo);
                if (status.Code != 201) 
                    return false;
            }

            return true;
        }

        public bool HasPublishResults(XmlDocument sessionXml)
        {
            return true;
        }

        public void LaunchPublishResults(XmlDocument sessionXml)
        {
            Process.Start(_tumblrApi.GetAccountInfo().TumbleLog.Url);
        }

        public bool HasSummaryInformation(XmlDocument sessionXml)
        {
            return false;
        }

        public void ShowSummaryInformation(IWin32Window parentWindow, XmlDocument sessionXml)
        {
            throw new NotImplementedException();
        }
    }
}
